<!-- 甘特图-->
<!-- http://localhost:5173/#/gantt?sevId=1789129970156244992 -->
<template>
  <el-alert
    v-if="isMobileVal"
    :title="mobileAlert"
    type="warning"
    center
    show-icon
    style="margin: 50px auto"
    :closable="false"
  />
  <div class="gantt-container" v-show="!isMobileVal&&hasEntity" v-title="ganttTitle">
    <div class="tips-desc">
      <span class="progress-status-point todo"></span>{{ todo }}
      <span class="progress-status-point doing"></span>{{ doing }}
      <span class="progress-status-point done"></span>{{ done }}
      <span class="progress-status-point over"></span>{{ delay }}
      <span class="progress-status-point process"></span>{{ actualProgress }}
    </div>
    <!-- <el-button
      v-if="!isMobileVal && canShareRef"
      :icon="Share"
      :loading="isSharingRef"
      class="share-btn"
      @click="share"
      size="small"
      >{{ shareBtn }}</el-button
    > -->
    <div ref="ganttRef" class="gantt" id="gantt"></div>
  </div>
  <div v-if="!isMobileVal&&!hasEntity" class="no-data">{{}}</div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { fetchData, insertShareInfo, fetchShareInfo } from '@/api/qygly'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { gantt } from 'dhtmlx-gantt'
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'
import { reqAllPlan } from '@/api/config/plan'
import { riskGanttColor, renderGantt } from './index'
const { VITE_DOMAIN_LOCATION } = import.meta.env
import { isMobile } from '@/utils/common.js'
import { Share } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user.js'
const store = useUserStore()
let canShareRef = ref(false)
let isSharingRef = ref(false)
const isMobileVal = ref(false)
const route = useRoute()
const ganttRef = ref()
const req = ref({})
const tasks = reactive({ data: [] })
const hasEntity = ref(true)// 是否有数据
import { usePltI18nStore } from '@/stores/i18n-plt'
const pltI18nStore = usePltI18nStore()

const {shareBtn,todo, doing, done, delay} = pltI18nStore.pltI18n.cisdi.gczx.frontEnd.common
const {actualProgress, ganttTitle, mobileAlert} = pltI18nStore.pltI18n.cisdi.gczx.frontEnd.gantt

const getData = async () => {
  tasks.data = []
  // 获取数据
  const res = await fetchData(req.value)
  const { entityRecordList } = res
  if(!entityRecordList) {
    hasEntity.value = false
  }else{
    hasEntity.value = true
    entityRecordList.map((item) => {
    const { ID, NAME, PLAN_FR, PLAN_DAYS, CC_WBS_RISK_ID } = item.textMap
    const findParent = entityRecordList.find(
      (record) => record.valueMap.ID == item.valueMap.CC_PRJ_STRUCT_NODE_PID,
    )
    if (
      item.valueMap.CC_PRJ_STRUCT_NODE_PID &&
      item.valueMap.CC_PRJ_STRUCT_NODE_PID != item.valueMap.ID &&
      findParent
    ) {
      // 如果有父节点，则添加parent
      tasks.data.push({
        id: ID,
        text: NAME,
        start_date: PLAN_FR,
        duration: PLAN_DAYS,
        parent: item.valueMap.CC_PRJ_STRUCT_NODE_PID,
        progress: item.valueMap.ACT_WBS_PCT ? item.valueMap.ACT_WBS_PCT / 100 : 0,
        open: true,
        status: item.valueMap.CC_WBS_PROGRESS_STATUS_ID,
      })
    } else {
      // 如果没有父节点,则不添加parent字段
      tasks.data.push({
        id: ID,
        text: NAME,
        start_date: PLAN_FR,
        duration: PLAN_DAYS,
        progress: item.valueMap.ACT_WBS_PCT ? item.valueMap.ACT_WBS_PCT / 100 : 0,
        open: false,
        status: item.valueMap.CC_WBS_PROGRESS_STATUS_ID,
        // color: riskGanttColor(item),
      })
    }
  })
  renderGantt(ganttRef.value, tasks)
  }
}
if (route.query.shareId) {
  // 若为查看共享的数据：
  onMounted(() => {
    isMobileVal.value = isMobile()
    fetchShareInfo({
      orgId: route.query.orgId,
      id: route.query.shareId,
    }).then((result) => {
      let tasks = JSON.parse(result.shareContextData).tasks
      renderGantt(ganttRef.value, tasks)
    })
  })
} else {
  onMounted(() => {
    if (!store.loginInfo.globalVarMap.P_CC_PRJ_IDS) {
      ElMessage({
        showClose: true,
        message: '当前没选择项目，请选择项目',
        type: 'warning',
        duration: 0,
        offset: 150,
      })
    } else {
      isMobileVal.value = isMobile()
      req.value = {
        ...reqAllPlan,
        sevId: route.query.sevId, // 通过路由区分现行计划、历史计划，具体值在企业云里配置
      }
      if (import.meta.env.MODE === 'development') {
        getData()
      }
      const { iframeId } = route.query
      const data = {
        mark: 'QYGLY',
        iframeId,
        isReqOrResp: true,
        type: 'READY_TO_FETCH',
        commId: 'READY_TO_FETCH',
      }
      window.parent.postMessage(data, '*')
      canShareRef.value = true
    }
  })
}

// 分享
const share = () => {
  isSharingRef.value = false
  const { id } = store.loginInfo.currentOrgInfo
  insertShareInfo({
    // test240511要换成具体登陆的组织ID，@SHARE_ID将由后端代入具体的shareId并保存到数据库：
    shareUrl: `../${VITE_DOMAIN_LOCATION}/#/gantt?orgId=${id}&shareId=@SHARE_ID`, //http://localhost:5173/
    // shareContextData用于保存页面状态：
    shareContextData: JSON.stringify({
      tasks: tasks,
    }),
  })
    .then((result) => {
      console.log(result)
      const data1 = {
        mark: 'QYGLY',
        iframeId: route.query.iframeId,
        isReqOrResp: true,
        type: 'CONFIG_SHARE',
        commId: 'CONFIG_SHARE',
        content: {
          shareInfo: result,
        },
      }
      window.parent.postMessage(data1, '*')
    })
    .finally(() => {
      isSharingRef.value = false
    })
}

// 接收企业云的数据
window.addEventListener(
  'message',
  async (e) => {
    req.value = {
      ...reqAllPlan,
      ...e.data.content, //企业云postmessage发过来的数据
      sevId: route.query.sevId, // 通过路由区分现行计划、历史计划，具体值在企业云里配置
    }
    // console.log('我收到的message', route.query.sevId, e.data.content)
    console.info('cisdi-gantt收到的message', e.data.content)

    if (e.data.mark !== 'QYGLY') {
      return
    } else {
      getData()
    }
  },
  false,
)
</script>

<style lang="scss" src="">
$todo-color: #606266; //rgb(96, 98, 102),#ebebeb
$done-color: #2daa98; //#2daa98,#63b47e
$doing-color: #ff9500; //#ff9500,#eec871
$over-color: #ff4949; //#ff4949,#e60012
$process-color: #299cb4; //#ff4949,#e60012
.gantt-container {
  height: 100vh;
  padding-top: 50px;

  .share-btn {
    position: fixed;
    right: 10px;
    top: 10px;
    z-index: 99;
  }

  .tips-desc {
    position: fixed;
    left: 10px;
    top: 10px;
    z-index: 99;
    font-size: 14px;
    color: #5c5c5c;
    display: flex;
    align-items: center;

    .progress-status-point {
      display: inline-block;
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin: 0 5px;

      &.todo {
        background-color: $todo-color;
      }

      &.doing {
        background-color: $doing-color;
      }

      &.done {
        background-color: $done-color;
      }
      &.over {
        background-color: $over-color;
      }
      &.process {
        background-color: $process-color;
      }
    }
  }
}
.gantt {
  height: calc(100vh - 60px);
  .gantt_task_line {
    min-width: 11px;
  }
  .todo {
    background-color: #dbdbdb;
    border: none;
    .gantt_task_content {
      color: rgb(96, 98, 102);
    }
  }
  .doing {
    background-color: #fcf4eb;
    border: none;
    .gantt_task_content {
      color: #ff9500;
    }
  }
  .done {
    background-color: #e4f9ed;
    border: none;
    .gantt_task_content {
      color: #2daa98;
    }
    .gantt_task_progress {
      background-color: #e4f9ed;
    }
  }
  .over {
    background-color: #fce6e6;
    border: none;
    .gantt_task_content {
      color: #ff4949;
    }
  }
}
</style>
